package org.example.queue.blockingQueue;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Administrator on 2018/6/14 0014.
 * 消费者 线程任务
 */
public class Consumer extends Thread {
    /**
     * blockingQueue：阻塞队列
     * countDownLatch：倒计数锁存器，用于将来告诉主线程消费者已经消费结束了
     * isExit：在收到生产者结束标识"exit"消息之前，消费者会一直循环阻塞的获取消息, 当isExit为true时，退出循环，消费任务结束
     * random：用于生产随机数
     */
    private BlockingQueue<String> blockingQueue;
    private CountDownLatch countDownLatch;
    public boolean isExit = false;
    private Random random;

    /**
     * 初始化参数值
     *
     * @param blockingQueue
     * @param countDownLatch
     */
    public Consumer(BlockingQueue blockingQueue, CountDownLatch countDownLatch) {
        this.blockingQueue = blockingQueue;
        this.countDownLatch = countDownLatch;
        random = new Random();
    }

    @Override
    public void run() {
        try {
            while (!isExit) {
                /**获取链式队列中头部元素，FIFO(先进先出)
                 * 队列中没有元素时，take会一直阻塞，获取到之后，队列原位置的元素就会被删除*/
                String info = blockingQueue.take();
                /**如果收到"exit"消息，则退出循环*/
                if ("exit".equals(info)) {
                    isExit = true;
                }
                System.out.println(Thread.currentThread().getName() + " 消费了消息：" + info);
            }
            /**倒计数锁存器计数减一*/
            countDownLatch.countDown();
            System.out.println(Thread.currentThread().getName() + " 消费者线程即将结束...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}